package com.lzh.listen;

import com.alibaba.fastjson.JSONObject;
import com.lzh.client.OrderClients;
import com.lzh.pojo.entity.TgOrder;
import com.lzh.pojo.repVo.BaseResp;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RabbitMqListen {
    @Autowired(required = false)
    JavaMailSender javaMailSender;

    @Autowired
    RedisTemplate redisTemplate;
    @Value("${spring.mail.username}")
    private String from;
    //定义日志
    public static Logger logger= LoggerFactory.getLogger(RabbitMqListen.class);

    @Autowired(required = false)
    OrderClients orderClients;
    @RabbitListener(queues = "tg-pay-queue")
    public void payQueue(String msg, Channel channel, Message message){
        try {
            logger.debug("进入到了取消支付的监听中。取消的订单号为：{}"+msg);
            //判断该订单的支付状态，如果状态还是为3的话，说明用户未在30秒内进行付款，则置为取消，如果状态已经为2，说明用户已经支付成功
            BaseResp byOrderid = orderClients.findByOrderId(msg);
            if (byOrderid.getCode()!=0){
                Object data = byOrderid.getData();
                String s = JSONObject.toJSONString(data);
                TgOrder tgOrder = JSONObject.parseObject(s, TgOrder.class);
                logger.debug("订单编号为：{}"+msg+"未在规定时间内付款，需要将其改为取消支付状态！");
                if (tgOrder.getOrderStatus()==3){
                    //远程调用order服务将该订单置为取消状态！
                    BaseResp baseResp = orderClients.updateStatus(msg, 4);
                    if (baseResp.getCode()==1){
                        logger.debug("订单编号为：{}"+msg+"取消支付成功!");
                    }
                }else {
                    logger.debug("订单编号为：{}"+msg+"支付成功!");
                }

            }
            //将该笔订单消息进行确认，已经被处理完成
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
